package com.jz.community.basecomm.net;

import android.content.Context;

import com.jz.community.basecomm.token.TokenUtil;
import com.jz.community.basecomm.net.retrofit.ApiException;
import com.jz.community.basecomm.net.retrofit.ErrorHandle;
import com.jz.community.basecomm.reflection.refreshtoken.RefreshTokenActionReflectUtils;
import com.jz.community.basecomm.utils.BaseSpUtils;

import java.io.IOException;
import java.net.SocketTimeoutException;

import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;

/**
 * Created by Tony.Fan on 2018/3/12 16:08
 */
public class OKHttpInterceptor implements Interceptor {
    private Context mContext;

    /**
     * @param context 需要传入一个界面相关的Context 因为需要处理 toast
     */
    public OKHttpInterceptor(Context context) {
        this.mContext = context;
    }

    @Override
    public Response intercept(Chain chain) throws IOException {
        Request.Builder requestBuilder = chain.request().newBuilder();
        requestBuilder = TokenUtil.addUserTokenIfPossible(mContext, requestBuilder);
        Request newReq = requestBuilder.build();
        Response response = chain.proceed(newReq);
        try {
            if (isTokenExpired(response)) {
                getRefreshToken();
                requestBuilder = TokenUtil.addUserTokenIfPossible(mContext, requestBuilder);
                Request newRequest = requestBuilder.build();
                //重新请求
                return chain.proceed(newRequest);
            } else {
                ErrorHandle errorHandle = new ErrorHandle(mContext);
                return errorHandle.handleResponseError(response);
            }
        } catch (SocketTimeoutException socketExp) {

        }
        return chain.proceed(chain.request());
    }

    /**
     * 根据Response，判断Token是否失效
     *
     * @param response
     * @return
     */
    private boolean isTokenExpired(Response response) {
        if (response.code() == ApiException.UNAUTHORIZED) {
            return true;
        }
        return false;
    }

    /**
     * 获取新的Token
     */
    private void getRefreshToken() {
        if (BaseSpUtils.getInstance().getIsLogin(mContext)) {
            RefreshTokenActionReflectUtils.jumpRefreshTokenPage(mContext);
        }
    }
}
